<?php

require_once($GLOBALS['BIB'] . "Objects/val.form.mex");
require_once($GLOBALS['BIB'] . "Pr_db/Transaction/comuns.php");
require_once('sql_queries.php');

class Transact {

    public function transaction($CorrespID, $PID, $TrnID, $TrnAffected, $CNC) {
        global $SYSTEMTASK, $sysTime, $SESSID, $sys, $db, $russlavBank, $__sysTFTImport_Directory, $__sys, $ORPOOL;
        $ORPOOL = $TrnAffected;
        $UserID = 0;
        if (!isset($SYSTEMTASK)) {
            $SYSTEMTASK = 'null';
        }
        if (isset($_SESSION[$SESSID])) {
            $UserID = $_SESSION[$SESSID];
        }
        $TrsResultCode = 0;
        if ($PID < 1 || $CorrespID < 1) {
            $error = 'Invalid parameters.';
        }
        MYTCONN();
        $transact_value = $TrnID;

        if (!isset($error)) {
            $GETCOMMETH = $GLOBALS['MYT']->db_array("SELECT *
            FROM trn_corrmethods
            INNER JOIN corresponsales ON CorrNumero = tcmtCorrespondent
            INNER JOIN trn_methodprocedures ON trmpPID = tcmtPID AND trmpMethod = tcmtMethod
            WHERE tcmtCorrespondent = $CorrespID AND tcmtPID = $PID");
            if (isset($_GET['pr'])) {
                $procedure = $_GET['pr'];
            } elseif ($GETCOMMETH[1]['trmpProcedureName'] == '') {
                die('Invalid Procedure Name');
            } else {
                $procedure = $GETCOMMETH[1]['trmpProcedureName'];
            }
            if (!isset($GETCOMMETH[1])) {
                $error = "Nao esta definido um metodo de comunicacao desta transaccao com o correspondente.";
            }
            if (!isset($error)) {
                if ($procedure == 'outgoingtransaction') {
                    $TrsID = $TrnID;
                } elseif ($GETCOMMETH[1]['tcmtMethod'] == 1) {
                    $TrsID = 0;
                } elseif ($GETCOMMETH[1]['tcmtMethod'] == 2) {
                    $TrsID = $transact_value;
                }
                if ($GETCOMMETH[1]['tcmtMethod'] == 1) {
                    include($GLOBALS['ROO'].'Libraries/Pr_db/TransactionFT/tft_default.php');
                    if (!isset($TrsResultCode) || $procedure == 'outgoingtransaction') {
                        $TrsResultCode = $TransmissionResultCode - 1;
                    } elseif (!isset($TrsResultCode) && isset($TransmissionResultCode)) {
                        $TrsResultCode = $TransmissionResultCode - 1;
                    } else {
                        $TrsResultCode = 0;
                    }
                } elseif ($GETCOMMETH[1]['tcmtMethod'] == 2) {
                    if (correspondenteRusslav($CorrespID)) {
                        $sql = '
                    select FraID as id
                    from officeschema.facturas
                    where
                    FraOrdenTrans is null
                    and FraStatus = 3
                    and FraCorresponsal = 306
                    and FraModo = 1;';

                        $result = $db->getall($sql);
                        $idDasRemessaAEnviar = array();
                        foreach ($result as $remessa) {
                            //echo $remessa->id . '<br />';
                            $sql = 'select officeschema.facturas.FraReferenciaCo as id
                            from officeschema.facturas
                            where fraid=' . $remessa->id . ';';
                            $result = $db->getall($sql);
                            $result = $result[0];
                            array_push($idDasRemessaAEnviar, $result->id);
                        }
                        foreach ($idDasRemessaAEnviar as $id) {



                            /* $result = $russlavBank->payOutGoing($id);
                              $result = $russlavBank->objectsIntoArray(simplexml_load_string($result));
                              if ($russlavBank->respostaOk($result)) {
                             */
                            echo'<script>alert("'
                            . 'Remessa enviada com sucesso\n' .
                            'RusslavBankId:' . $id .
                            '");</script>';

                            /* TODO: estes codigos têm que afectar o lote e não apenas a ultima remessa */
                            //para ficar ok mais tarde

                            $TrsResultCode = 1;
                            /* } else {
                              echo 'resposta ko';
                              echo $result['@attributes']['ERR_TEXT'];
                              echo'<script>alert("'
                              . $result['@attributes']['ERR_TEXT'] . '\n' .
                              'RusslavBankId:' . $id .
                              '");</script>';

                              //para ficar com o erro mais tarde
                              $TransmissionResultCode = 1;
                              $TrsResultCode = 0;
                              } */
                        }
                    }
                }
            }
            if ($TrsResultCode == 0) {
                # Show Error
                if (isset($tlDocument_ERR)) {
                    $error = 'TLD:' . $tlDocument_ERR;
                } elseif (isset($blDocument_ERR)) {
                    $error = 'BLD:' . $blDocument_ERR;
                } elseif (isset($Exception_error)) {
                    $error = 'Exc:' . $Exception_error;
                } else {
                    $error = 'Nada pra processar.';
                }
            }
            #LOG
            $log_file = $GLOBALS['DOC'] . 'syslog/transact/trn_task' . date("Ym") . '.log';
            $logstring = '[' . $sysTime . ']	' . $_SERVER['REMOTE_ADDR'] . '	' . $PID . '	' . $UserID . ' ' . $SYSTEMTASK . ' ' . $GETCOMMETH[1]['tcmtID'] . ' ' . $CorrespID . ' ' . $TrsResultCode . ' ' . $TrsID;
            if (isset($error)) {
                $logstring .= ' ' . $error;
            }
            if (!file_exists($log_file)) {
                if (!fopen($log_file, 'w')) {
                    $error = 'could not log transaction.';
                }
            }
            error_log($logstring . PHP_EOL, 3, $log_file);
            # Register Task
            $row = tuga_multiquery("CALL transact_tasklog
                                    ($SYSTEMTASK,{$GETCOMMETH[1]['tcmtID']},'$sysTime',$UserID,$TrsResultCode,$TrsID); SELECT @TaskID;");
            $trnTask = $row[0][0];
        }
        if (isset($error) && !isset($_syspause)) {
            return '<script type="javascript/text">alert(\'' . $error . '\');</script>';
        }
    }

    function tft_MoveFileToOutgoing($filename, $GETCOMMETH, $GetSettings, $TransactionFTName) {
        if (isset($GETCOMMETH[1])) {
            ## copia ficheiro para pasta ftp
            if (is_dir($GetSettings[1]['set_Valor'] . '//' . $GETCOMMETH[1]['CorrAgente'] . '//OUT//')) {
                if (!copy($filename, $GetSettings[1]['set_Valor'] . '//' . $GETCOMMETH[1]['CorrAgente'] . '//OUT//' . $TransactionFTName)) {
                    return $Exception_error = 'Error copying file.';
                }
            } else {
                return $error = 'FTP_CONFIG:No directory found.';
            }
        }
    }

    function sql_GetTransactionRows($PID, $CorrespID, $QueryIDs) {
        if ($PID == 162) {
            global $Trn162;
            return preg_replace("/#ID#/", $QueryIDs, preg_replace("/#Corr#/", $CorrespID, $Trn162));
        } elseif ($PID == 170) {
            global $Trn170;
            return preg_replace("/#LastDate#/", $QueryIDs, preg_replace("/#Corr#/", $CorrespID, $Trn170));
        } elseif ($PID == 178) {
            global $Trn178;
            return preg_replace("/#LastDate#/", $QueryIDs, preg_replace("/#Corr#/", $CorrespID, $Trn178));
        }
    }

    function tft_OutputFile($TransactionModel, $filename, $max, $CNC) {

        if (!file_exists($filename)) {
            $List = $GLOBALS['MYT']->db_array($max);
            if (isset($List[1])) {
                include($TransactionModel);
            } else {
                $error = 'Transmissão vazia.';
            }
        } else {
            $error = 'Erro de transmissao: ficheiro já Existe';
        }
        if (isset($error)) {
            return false;
            return $error;
        } else {
            return true;
        }
    }

    public function tft_OutputSingleFile($TransactionModel, $DatadirTransmitionOut, $max, $CNC, $GETCOMMETH, $GetSettings, $TrnTime, $CorrCode, $CorrFName, $CorrExt) {
        $GetModelProperties = $GLOBALS['MYT']->db_array("SELECT ff_zftransactionid FROM hd_fileformats WHERE REF = ".$GETCOMMETH[1]['tcmtLink']);
        $GET = $GLOBALS['MYT']->db_array($max);
        for ($y = 1; $y <= $GET[0]; $y++) {
            $FileTransactionCoID = $GET[$y]['Trs_CorrTrans'];
            if ($GetModelProperties[1]['ff_zftransactionid'] == 1) {
                $FileTransactionCoID = str_pad((int) $FileTransactionCoID, 10, "0", STR_PAD_LEFT);
                $GET[$y]['FraIncReferenciaCo'] = str_pad((int) $GET[$y]['FraIncReferenciaCo'], 10, "0", STR_PAD_LEFT);
            }
            $TransactionFTName = transaction_filenames($DatadirTransmitionOut, $TrnTime, $FileTransactionCoID, $CorrCode, $CorrFName, $CorrExt);
            if (!file_exists($TransactionFTName)) {
                if (isset($GET[1])) {
                    $handle = fopen($DatadirTransmitionOut . $TransactionFTName, "x");
                    include($TransactionModel);
                    fwrite($handle, $log);
                    fclose($handle);
                    $this->tft_MoveFileToOutgoing($DatadirTransmitionOut . $TransactionFTName, $GETCOMMETH, $GetSettings, $TransactionFTName);
                } else {
                    $error = 'Transmissão vazia.';
                }
            } else {
                $error = 'Erro de transmissao: ficheiro já Existe';
            }
            if (isset($error)) {
                return false;
                return $error;
            } else {
                return true;
            }
        }
    }

}
